﻿using CSRedis;
using Furion.FriendlyException;
using Gt3;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using System.Web;


public class GeetestOpenApi
{

    public IDictionary<string, string> paramDict = new Dictionary<string, string> { { "gt", GeetestConfig.GEETEST_ID } };

    public class ResBody
    {
        public string status { get; set; }
    }

    public async void CheckStatus()
    {
        while (true)
        {
            //var res = await Http.Get<ResBody>(GeetestConfig.BYPASS_URL, paramDict);

            var res = await Http.Get<ResBody>(GeetestConfig.BYPASS_URL);

            await RedisHelper.SetAsync(GeetestConfig.GEETEST_BYPASS_STATUS_KEY, res.status);

            await RedisHelper.SetAsync("ttt", DateTime.Now.ToString());


            Thread.Sleep(millisecondsTimeout: GeetestConfig.CYCLE_TIME);
        }
    }

    private async Task<string> GetBypassCache()
    {
        return await RedisHelper.GetAsync(GeetestConfig.GEETEST_BYPASS_STATUS_KEY);
    }



    public async Task<GeetestLibResult> FirstRegister()
    {

        GeetestLib gtLib = new GeetestLib(GeetestConfig.GEETEST_ID, GeetestConfig.GEETEST_KEY);

        string userId = "test";

        string digestmod = "md5";

        IDictionary<string, string> paramDict = new Dictionary<string, string> { { "digestmod", digestmod }, { "user_id", userId }, { "client_type", "web" }, { "ip_address", "127.0.0.1" } };

        string bypass_cache = await GetBypassCache();

        GeetestLibResult result;

        //if (bypass_cache == "success")
        //{
            result = gtLib.Register(digestmod, paramDict);
        //}
        //else
        //{
        //    result = gtLib.LocalRegister();
        //}
        return result;
    }

    public async Task<bool> SecondValidate(string challenge, string validate, string seccode)
    {
        GeetestLibResult result;

        IDictionary<string, string> paramDict = new Dictionary<string, string> { };

        GeetestLib gtLib = new GeetestLib(GeetestConfig.GEETEST_ID, GeetestConfig.GEETEST_KEY);

        //string bypass_cache = await GetBypassCache();

        //if (bypass_cache is null) throw Oops.Oh("获取缓存的bypass状态发生异常");


        //if (bypass_cache == "success")
        //{
            result = gtLib.SuccessValidate(challenge, validate, seccode, paramDict);
        //}
        //else
        //{
        //    result = gtLib.FailValidate(challenge, validate, seccode);
        //}


        if (result.GetStatus() == 1) return true;


        throw Oops.Oh(result.GetMsg());

    }

}

